//得到时间格式2018-10-02
const formatDate = (date) => {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    return [year, month, day].map(formatNumber).join('/');
};

const formatNumber = (n) => {
    n = n.toString();
    return n[1] ? n : '0' + n;
};
//todate默认参数是当前日期，可以传入对应时间 todate格式为2018-10-05
function getDates(days, todate) {
    var dateArry = [];
    for (var i = 0; i < days; i++) {
        var dateObj = dateLater(todate, i);
        dateArry.push(dateObj);
    }
    return dateArry;
}

function dateLater(dates, later) {
    let dateObj = {};
    let show_day = new Array(
        '周日',
        '周一',
        '周二',
        '周三',
        '周四',
        '周五',
        '周六'
    );
    let date = new Date(dates);
    date.setDate(date.getDate() + later);
    let day = date.getDay();
    let yearDate = date.getFullYear();
    let month =
        date.getMonth() + 1 < 10
            ? '0' + (date.getMonth() + 1)
            : date.getMonth() + 1;
    let dayFormate =
        date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    dateObj.time = yearDate + '-' + month + '-' + dayFormate;
    dateObj.week = show_day[day];
    return dateObj;
}

// 处理距离
function formatDistance(distance) {
    if (!distance) return;
    let formatDistance;
    if (typeof distance !== 'number') {
        distance = parseInt(distance);
    }
    if (distance < 100) {
        formatDistance = '<100m';
    } else if (distance < 1000) {
        formatDistance = `${distance}m`;
    } else {
        formatDistance = `${(distance / 1000).toFixed(1)}km`;
    }
    return formatDistance;
}

/**
 *
 * @param {'yyyy-mm-dd hh:mm:ss'} time
 */
function getTimePart(time) {
    var regex = /^(\d{4})-(\d{2})-(\d{2})\s(\d{2}):(\d{2}):(\d{2})$/;
    time.match(regex);
    return {
        year: RegExp.$1,
        month: RegExp.$2,
        day: RegExp.$3,
        hour: RegExp.$4,
        minute: RegExp.$5,
        second: RegExp.$6,
        format: `${RegExp.$1}-${RegExp.$2}-${RegExp.$3} ${RegExp.$4}:${RegExp.$5}`,
        date: `${RegExp.$1}-${RegExp.$2}-${RegExp.$3}`,
        formatShort: `${RegExp.$1}-${RegExp.$2}-${RegExp.$3}`,
    };
}

function getCheckInTime(time) {
    const regex = /^(\d{4})-(\d{2})-?(\d{2})?$/;
    time.match(regex);
    const format = RegExp.$3
        ? `${RegExp.$1}-${RegExp.$2}-${RegExp.$3}`
        : `${RegExp.$1}-${RegExp.$2}`;
    return format;
}

/**
 * 判断对象的属性是否都为空
 * @param {} object
 */
function isAllEmptyObject(object) {
    return (
        Object.values(object).findIndex(
            (item) => item !== '' && item !== undefined && item !== null
        ) < 0
    );
}

module.exports = {
    formatDate: formatDate,
    getDates: getDates,
    formatDistance,
    getTimePart,
    isAllEmptyObject,
    getCheckInTime,
};
